package com.dev.security.setting.controllers;

import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.dev.security.login.beans.LoginUser;
import com.dev.security.login.service.LoginManager;
import com.dev.security.setting.beans.UserSetting;
import com.dev.security.setting.beans.UserSettingId;
import com.dev.security.setting.service.IUserSettingService;
import com.dev.security.util.Response;

/**
 * @author 飘渺青衣
 * @see
 */
@Controller
@RequestMapping("/user/setting/")
public class UserSettingController {

	@Resource
	private IUserSettingService userSettingService;
	
	@Resource
	private LoginManager loginManager;
	
	@RequestMapping("value")
	public @ResponseBody String value(
			HttpServletRequest request, 
			HttpServletResponse response, 
			String field_name) {
		LoginUser loginUser = this.loginManager.getLoginUser(request, response);
		UserSetting setting = this.userSettingService.findUserSetting(
				loginUser.getUserId(), StringUtils.trimToEmpty(field_name));
		if(setting != null) {
			return setting.getValue();
		}
		return "";
	}
	
	@RequestMapping("values")
	public @ResponseBody Map<String, String> values(
			HttpServletRequest request, 
			HttpServletResponse response, 
			String field_name) {
		LoginUser loginUser = this.loginManager.getLoginUser(request, response);
		return this.userSettingService.findUserSettingMap(loginUser.getUserId());
	}
	
	@RequestMapping("set")
	public @ResponseBody Response set(
			HttpServletRequest request, 
			HttpServletResponse response, 
			String field_name, String value) {
		LoginUser loginUser = this.loginManager.getLoginUser(request, response);
		UserSetting setting = new UserSetting();
		setting.setId(new UserSettingId(loginUser.getUserId(), StringUtils.trimToEmpty(field_name)));
		setting.setValue(StringUtils.trimToEmpty(value));
		this.userSettingService.save(setting);
		return new Response(true, setting);
	}
	
}
